﻿/*********************************************************************************************************************
VanguardDocumentation, Function GetBaseEntity

© 2014 Erik Ackerholm

This file is part of SqlVanguard.

SqlVanguard is free software: you can redistribute it and/or modify it under the terms of the GNU General Public 
License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later 
version.

SqlVanguard is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied 
warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with SqlVanguard. If not, see 
<http://www.gnu.org/licenses/>.
*********************************************************************************************************************/

if
	not exists (
		select *
		from sys.schemas as s
			inner join sys.objects as o on (s.schema_id = o.schema_id)
		where s.name = 'VanguardDocumentation' and o.[type] = 'FN'
			and o.name = 'GetBaseEntity'
	)
begin
	declare @SqlCommand as nvarchar(max);
	set @SqlCommand = '
		create function VanguardDocumentation.GetBaseEntity ()
			returns nvarchar(255)
		as
		begin
			return ''Function GetBaseEntity is not implemented yet!'';
		end;
	';
	execute (@SqlCommand);
end;
GO

alter function VanguardDocumentation.GetBaseEntity (
	/*****************************************************************************************************************
	Fetches the name of a base entity, that has previously been set (in the same session).
	
	Empty values are represented in the output by null.
	*****************************************************************************************************************/
)
	returns nvarchar(512)
as
begin
	
	declare @EntityName as nvarchar(512);
	
	set @EntityName = (
		select top (1) Variables.value('(/Variables/BaseEntity/@Name)[1]', 'nvarchar(512)')
		from VanguardDocumentation.SessionVariables
		where SessionID = @@spid
			and SessionStartTime = (select login_time from sys.dm_exec_sessions where session_id = @@spid)
	);
	
	return nullif(@EntityName, '');
	
end;
GO

grant execute on VanguardDocumentation.GetBaseEntity to VanguardDocumentationReader;
grant execute on VanguardDocumentation.GetBaseEntity to VanguardDocumentationWriter;
GO




